package com.sphd.education.activitys;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.info.LessonInfo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 预约报名
 */
public class AddNameActivity extends BaseActivity implements View.OnClickListener {
    String TAG = "AddNameActivity.class";
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.lesson_img)
    ImageView lessonImg;
    @Bind(R.id.lesson_name_textview)
    TextView lessonNameTextview;
    @Bind(R.id.lesson_jianjie)
    TextView lessonJianjie;
    @Bind(R.id.student_num)
    TextView studentNum;
    @Bind(R.id.addname_btn)
    Button addnameBtn;
    @Bind(R.id.relation_phone_img)
    ImageView relationPhoneImg;
    @Bind(R.id.relation_phone)
    TextView relationPhone;
    @Bind(R.id.relation_address)
    TextView relationAddress;
    @Bind(R.id.student_class_name)
    TextView studentClassName;
    @Bind(R.id.class_name)
    TextView className;
    @Bind(R.id.teacher_name)
    TextView teacherName;
    @Bind(R.id.class_time)
    TextView classTime;
    @Bind(R.id.class_open_time)
    TextView classOpenTime;
    @Bind(R.id.class_over_time)
    TextView classOverTime;
    @Bind(R.id.up_go_time)
    TextView upGoTime;
    @Bind(R.id.lesson_money)
    TextView lessonMoney;
    private Bundle bundle;
    private Intent intent;
    LessonInfo lessonInfo;
    private Context context;
    MyInfo myInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_name);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//这是自带的箭头的返回的监听
            }
        });
        initView();
    }

    @Override
    public void initView() {
        myInfo = DataSupport.find(MyInfo.class, 1);
        intent = getIntent();
        context = AddNameActivity.this;
        bundle = intent.getBundleExtra(EducationIntentKey.LESSON);
        lessonInfo = (LessonInfo) bundle.getSerializable(EducationIntentKey.LESSON_INFO);
        ImageLoader.getInstance().displayImage(EducationUrl.HttpTitle +"/"+ lessonInfo.getImage(), lessonImg, setLessonImg());

        lessonNameTextview.setText("欢迎加入" + lessonInfo.getSchoolName());
        studentClassName.setText("课程：" + lessonInfo.getName());
        studentNum.setText("招生人数" + lessonInfo.getAppliedSize() + "/" + lessonInfo.getAllSize());
        className.setText("班级：" + lessonInfo.getBanji());
        if (TextUtils.isEmpty(lessonInfo.getTeacherName())) {
            teacherName.setText("班主任:暂无");
        } else {
            teacherName.setText("班主任:" + lessonInfo.getTeacherName());
        }

        classTime.setText("课时" + lessonInfo.getPeriod());
        if (!TextUtils.isEmpty(lessonInfo.getBeginTime())) {
            String open = lessonInfo.getBeginTime();
            open = open.replaceAll("-", ".");
            String[] strs = open.split("[ ]");
            classOpenTime.setText("开课时间:" + strs[0].toString());
        }
        if (!TextUtils.isEmpty(lessonInfo.getEndTime())) {
            String over = lessonInfo.getEndTime();
            over = over.replaceAll("-", ".");
            String[] stro = over.split("[ ]");
            classOverTime.setText("毕业时间:" + stro[0].toString());
        }
        upGoTime.setText("上课时间：" + lessonInfo.getClassSchedule());
        lessonMoney.setText(lessonInfo.getRealTuition() + "元");
        relationPhone.setText("热线电话：" + lessonInfo.getPhone());
        relationAddress.setText("上课地址：" + lessonInfo.getPlace());

        addnameBtn.setOnClickListener(this);
    }

    @Override
    public void findViewById() {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        myInfo = DataSupport.find(MyInfo.class, 1);
        Log.e("onRestart", "onRestart");
    }

    @Override
    public void myNet() {
        String url = EducationUrl.HttpTitle + EducationUrl.SignUp + "memberId=" +
                myInfo.getUserid() + "&classId=" + lessonInfo.getLesson_id();
        Log.e(TAG, "url=" + url);
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("response", response);
                if (response.equals("success")) {
                    EducationUrl.showToast(context, "预约成功");
                    finish();
                } else if (response.equals("error")) {
                    EducationUrl.showToast(context, "Sorry，您已报过此班了。");
                    finish();
                }else if (response.equals("more")){
                    EducationUrl.showToast(context, "预约人数已满，请致电学校或选择别的课程。");
                    finish();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.toString());
            }
        });
        EducationApplication.getRequestQueue().add(stringRequest);
    }

    private void getList(JSONObject response) {
        Log.e("AddNameActivity.class", response.toString());
    }

    @Override
    public void onClick(View v) {
        if (myInfo == null || myInfo.getUserid() == 0) {
//            Log.e("myInfo.getUserid()",myInfo.getUserid()+"");
            EducationUrl.showToast(context, "尚未登录功");
            intent.setClass(context, LoginActivity.class);
            startActivity(intent);
        } else {
            myNet();
        }
    }

    @OnClick(R.id.relation_phone_img)
    public void callTel() {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + lessonInfo.getPhone()));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        startActivity(intent);
    }
}
